import { createRouter, createWebHistory } from 'vue-router'
import { PieChart, VideoCamera, Upload, Warning, TrendCharts, Setting } from '@element-plus/icons-vue'

// 动态导入页面组件
const Dashboard = () => import('../pages/Dashboard.vue')
const Cameras = () => import('../pages/Cameras.vue')
const FileDetection = () => import('../pages/FileDetection.vue')
const Alerts = () => import('../pages/Alerts.vue')
const Statistics = () => import('../pages/Statistics.vue')
const SystemSettings = () => import('../pages/SystemSettings.vue')
const SceneManagement = () => import('../pages/SceneManagement.vue')

const routes = [
  {
    path: '/',
    redirect: '/dashboard'
  },
  {
    path: '/dashboard',
    name: 'dashboard',
    component: Dashboard,
    meta: {
      title: '数据看板',
      icon: PieChart,
      requiresAuth: true
    }
  },
  {
    path: '/cameras',
    name: 'cameras',
    component: Cameras,
    meta: {
      title: '摄像头监控',
      icon: VideoCamera,
      requiresAuth: true
    }
  },
  {
    path: '/file-detection',
    name: 'fileDetection',
    component: FileDetection,
    meta: {
      title: '文件检测',
      icon: Upload,
      requiresAuth: true
    }
  },
  {
    path: '/alerts',
    name: 'alerts',
    component: Alerts,
    meta: {
      title: '告警管理',
      icon: Warning,
      requiresAuth: true
    }
  },
  {
    path: '/statistics',
    name: 'statistics',
    component: Statistics,
    meta: {
      title: '统计分析',
      icon: TrendCharts,
      requiresAuth: true
    }
  },
  {
    path: '/system',
    name: 'system',
    component: SystemSettings,
    meta: {
      title: '系统设置',
      icon: Setting,
      requiresAuth: true
    }
  },
  {
    path: '/scene-management',
    name: 'sceneManagement',
    component: SceneManagement,
    meta: {
      title: '场景管理',
      requiresAuth: true
    }
  },
  // 404页面
  {
    path: '/:pathMatch(.*)*',
    name: 'notFound',
    component: () => import('../pages/NotFound.vue'),
    meta: {
      title: '页面不存在',
      hiddenBreadcrumb: true
    }
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes,
  // 滚动行为配置
  scrollBehavior(to, from, savedPosition) {
    if (savedPosition) {
      return savedPosition
    } else {
      return { top: 0 }
    }
  }
})

// 全局前置守卫
router.beforeEach((to, from, next) => {
  // 设置页面标题
  document.title = to.meta.title ? `${to.meta.title} - 智能交通监控系统` : '智能交通监控系统'
  
  // 检查权限（示例）
  if (to.meta.requiresAuth) {
    // 这里可以根据实际需求检查用户是否已登录
    // 例如检查localStorage中的token
    const token = localStorage.getItem('token')
    if (!token) {
      // 如果未登录，可以重定向到登录页
      // 目前系统没有登录页，所以直接放行
      // next({ path: '/login' })
    }
  }
  
  next()
})

// 全局后置守卫
router.afterEach((to, from) => {
  // 这里可以添加页面切换后的操作，如记录访问日志等
  console.log(`页面切换: ${from.name || '未知'} -> ${to.name || '未知'}`)
})

export default router